package com.danieltoms.gcSync;

import javax.microedition.pim.PIM;
import javax.microedition.pim.PIMException;

import net.rim.blackberry.api.pdap.BlackBerryContactList;
import net.rim.device.api.ui.UiApplication;

import com.danieltoms.gcSync.contact.ContactListListener;
import com.danieltoms.gcSync.google.feed.GoogleClientLoginFeed;
import com.danieltoms.gcSync.resources.GcSyncResResource;
import com.danieltoms.gcSync.screens.LoginScreen;
import com.danieltoms.gcSync.screens.StatusScreen;
import com.danieltoms.gcSync.util.Messages;

public class GcSync extends UiApplication
{
	private static ContactListListener _contactListener = null;

	private SyncThread _syncThread = null;
	private SyncStatus _syncStatus = null;
	private static Messages _messages = new Messages(GcSyncResResource.BUNDLE_ID, GcSyncResResource.BUNDLE_NAME);

	public static Messages getMessages()
	{
		return _messages;
	}

	public static void main(String[] args)
	{
		GcSync theApp = new GcSync();
		theApp.enterEventDispatcher();
	}

	public SyncStatus getSyncStatus()
	{
		return _syncStatus;
	}

	public void resetSyncStatus()
	{
		_syncStatus = new SyncStatus();
	}

	public SyncThread getSyncThread()
	{
		return _syncThread;
	}

	public GcSync()
	{

		_syncStatus = new SyncStatus();
		_syncThread = new SyncThread();

		pushScreen(new StatusScreen());

		if (GcSyncStore.instance().getEmail() == null || GcSyncStore.instance().getEmail().equals(""))
		{
			pushScreen(new LoginScreen());

		}
		else
			addContactListener();

	}

	public ContactListListener getContactListListener()
	{
		return _contactListener;
	}

	public void addContactListener()
	{
		if (GcSyncStore.instance().getEmail() != null || !GcSyncStore.instance().getEmail().equals(""))
		{
			if (_contactListener == null)
			{
				try
				{
					_contactListener = new ContactListListener();

					BlackBerryContactList list = (BlackBerryContactList) PIM.getInstance().openPIMList(
					        PIM.CONTACT_LIST, PIM.READ_ONLY);

					list.addListener(_contactListener);

				}
				catch (PIMException e)
				{
					// TODO handle
					e.printStackTrace();
				}
			}
		}
	}

	public void removeContactListener()
	{
		if (this.getContactListListener() != null)
		{
			try
			{

				BlackBerryContactList list = (BlackBerryContactList) PIM.getInstance().openPIMList(PIM.CONTACT_LIST,
				        PIM.READ_ONLY);

				list.removeListener(_contactListener);
				System.out.println("Contact listener removed");
			}
			catch (PIMException e)
			{
				// TODO Handle
				e.printStackTrace();
			}

			_contactListener = null;
		}
	}

	public void resetSyncThread()
    {
		_syncThread = new SyncThread();   
    }
}
